package com.qf.air.index;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

/**
 * @author 何星宇
 * @version V1.0
 * @Date 2021/11/4 9:57
 */
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = {
        "classpath:applicationContext-service.xml"
})
public class listEsTest {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    public void list() throws IOException {
        //创建指定的request
        SearchRequest request = new SearchRequest();
        request.indices("air_index");

        //封装查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        MatchQueryBuilder districtId = QueryBuilders.matchQuery("districtId", "3");
        MatchQueryBuilder monitoringStation = QueryBuilders.matchQuery("monitoringStation", "阿");
        RangeQueryBuilder monitorTime = QueryBuilders.rangeQuery("monitorTime").gte("2021-03-23").lte("2021-11-04");

        BoolQueryBuilder bool = QueryBuilders.boolQuery().must(districtId).must(monitoringStation).must(monitorTime);

        sourceBuilder.query(bool);
        sourceBuilder.from(1);
        sourceBuilder.size(10);
        sourceBuilder.sort("_id", SortOrder.DESC);

        //封装到request
        request.source(sourceBuilder);

        //发送请求，得到响应
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //输出数据
        for (SearchHit hit : response.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }


}
